import React, { useEffect, useMemo, useState } from 'react';
import { history } from 'umi'
import { Card, Button, Form, Input, Select, Radio, DatePicker, Divider, Row, Col, message } from 'antd';
import moment from 'moment';
import { BottomAction } from '@/components';
import pageTabUtil from '@/utils/pageTabUtil';
import { useRequest } from '@/hooks';
// import Dimension from '@/components/Custom/Dimension';
import { hasWorkFlowByType } from '@/pages/WorkFlow/utils';
import { updateJobRankToHistory, updateJobRankTypeToHistory, fetchGradeType, fetchGrade } from './service';

import styles from './edit.less';

function disabledDate(current) {
    return current && current < moment().endOf('day');
}

const formLayout = {
    wrapperCol: { span: 18 },
    labelCol: { span: 6 }
};

const requiredRules = msg => [{ required: true, message: `请输入${msg || '必填项'}` }];
const rangeRules = (min, max) => ({ min, max, message: `请输入${min}-${max}个字符` });
// 暂时不需要此功能，先留着
// const rankDimensionsRules = () => [
//     {
//         required: true,
//         message: '评定维度至少需要一条'
//     },
//     {
//         validator(_, value, callback) {
//             const errMsg = '维度或者描述不能为空，维度数量不能大于20条，且描述字段最多200字符';
//             const validatorMap = {
//                 hasEmpty: {
//                     handler: () =>
//                         (value || []).some(item => {
//                             if (!item.dimensionTypeName || !item.demand) {
//                                 return true;
//                             }
//                             return false;
//                         })
//                 },
//                 isExceed: {
//                     handler: () => value && value.length > 20
//                 },
//                 hasMaxLen: {
//                     handler: () =>
//                         (value || []).some(item => {
//                             if (item.demand && item.demand.length > 200) {
//                                 return true;
//                             }
//                             return false;
//                         })
//                 }
//             };

//             const hasError = Object.keys(validatorMap).some(validatorKey => {
//                 const { handler } = validatorMap[validatorKey];
//                 if (handler()) {
//                     callback(errMsg);
//                     return true;
//                 }
//                 return false;
//             });

//             if (!hasError) callback();
//         }
//     }
// ];

/**
 * immediateEffect 立即生效
 * effectiveOnTime 按时生效
 */
const auditEffectFlagEnum = {
    immediateEffect: 0,
    effectiveOnTime: 1
};

const operationType = {
    add: 0,
    edit: 1,
    delete: 2
};

const JobRankEdit = ({ form, location }) => {
    const { getFieldDecorator } = form;
    const { query } = location;
    const { type, category, rankCode, rankTypeCode } = query;
    const [startTimeValue, setStartTimeValue] = useState(null);
    const [rankTypeNameState, setRankTypeNameState] = useState(null);

    const fetchGradeRankTypeSuccess = result => {
        const { code, data = {} } = result;
        if (code === 10000) {
            const { institutionName, institutionType, startTime, rankTypeName, rankTypeDesc, auditEffectFlag } = data;

            if (auditEffectFlag === auditEffectFlagEnum.effectiveOnTime) {
                setStartTimeValue(moment(startTime));
            }

            if (category === 'postRankType') {
                form.setFieldsValue({
                    applyDate: moment().format('YYYY-MM-DD'),
                    institutionName,
                    institutionType,
                    institutionNo: '',
                    institutionIntroduce: '',
                    rankTypeName,
                    rankTypeDesc,
                    auditEffectFlag:
                        auditEffectFlag !== undefined ? auditEffectFlag : auditEffectFlagEnum.immediateEffect,
                    modifyRemark: ''
                });
            }

            setRankTypeNameState(rankTypeName);
        }
    };

    const fetchGradeRankSuccess = result => {
        const { code, data } = result;
        if (code === 10000) {
            const {
                institutionName,
                institutionType,
                startTime,
                rankValue,
                rankDesc,
                auditEffectFlag,
                rankDimensions,
                rankName
            } = data;

            if (auditEffectFlag === auditEffectFlagEnum.effectiveOnTime) {
                setStartTimeValue(moment(startTime));
            }

            form.setFieldsValue({
                institutionName,
                institutionType,
                institutionNo: '',
                institutionIntroduce: '',
                rankValue,
                rankDesc,
                auditEffectFlag,
                rankDimensions,
                rankName,
                modifyRemark: ''
            });
        }
    };

    // 职级序列
    const { run: getGradeRankType } = useRequest(() => fetchGradeType(rankTypeCode), {
        manual: true,
        onSuccess: fetchGradeRankTypeSuccess
    });

    // 职级
    const { run: getGradeRank } = useRequest(() => fetchGrade(rankCode), {
        manual: true,
        onSuccess: fetchGradeRankSuccess
    });

    // 添加到历史表
    const { loading: flowRankLoading, run: addGradeRankToHistory } = useRequest(updateJobRankToHistory, {
        manual: true
    });

    const { loading: flowRankTypeLoading, run: addGradeRankTypeToHistory } = useRequest(updateJobRankTypeToHistory, {
        manual: true
    });

    const isPostRankType = useMemo(() => {
        if (category === 'postRankType') {
            return true;
        }
        return false;
    }, [category]);

    useEffect(() => {
        // 判断是新增还是编辑，编辑需要请求 fetch 数据，未完成
        if ((type === 'edit' || type === 'delete') && category) {
            if (category === 'postRankType') {
                getGradeRankType();
            } else {
                getGradeRank();
            }
        }
    }, [type, category, getGradeRankType, getGradeRank]);

    // 获取职级序列
    useEffect(() => {
        if (category === 'postRank' && rankTypeCode) {
            getGradeRankType(rankTypeCode);
        }
    }, [category, getGradeRankType, rankTypeCode]);

    const pageTitle = useMemo(() => {
        if (type && (category === 'postRankType' || category === 'postRank')) {
            const pageName = category === 'postRankType' ? '职级序列' : '职级';
            switch (type) {
                case 'edit':
                    return `编辑${pageName}`;
                case 'add':
                    return `新增${pageName}`;
                case 'delete':
                    return `删除${pageName}`;
                default:
                    return '';
            }
        }
        return '';
    }, [type, category]);

    const handleCancel = () => {
        pageTabUtil.goBack();
    };

    const goToWorkFlow = async (workFlowUrl, data) => {
        history.push(`${workFlowUrl}${data}`);
    };

    const updateToHistory = async (formData, workFlowUrl) => {
        let result;
        if (category === 'postRankType') {
            result = await addGradeRankTypeToHistory(formData);
        }

        if (category === 'postRank') {
            result = await addGradeRankToHistory(formData);
        }

        const { code, data, msg } = result || {};
        if (code === 10000) {
            goToWorkFlow(workFlowUrl, data);
        } else {
            message.error(msg);
        }
    };

    const handleSubmit = () => {
        form.validateFields(async (err, values) => {
            if (!err) {
                const { startTime } = values;
                const formatFormValues = {};
                if (startTime) {
                    formatFormValues.startTime = moment(startTime).format('YYYY-MM-DD HH:mm:ss');
                }

                const formData = {
                    ...values,
                    ...formatFormValues,
                    rankTypeCode
                };

                if (type === 'edit') {
                    formData.operationType = operationType.edit;
                } else if (type === 'delete') {
                    formData.operationType = operationType.delete;
                } else {
                    formData.operationType = operationType.add;
                }

                let workFlowUrlObj;

                if (category === 'postRankType') {
                    workFlowUrlObj = await hasWorkFlowByType('OrgRankTypeApply');
                }

                if (category === 'postRank') {
                    workFlowUrlObj = await hasWorkFlowByType('OrgRankApply');
                    formData.rankCode = rankCode;
                }

                const { workFlowUrl } = workFlowUrlObj;
                if (workFlowUrl) {
                    updateToHistory(formData, workFlowUrl);
                }
            }
        });
    };
    // 职级校验
    const rankValueRule = value => [
        ...value('职级'),
        {
            pattern: /^[a-zA-Z0-9]{1,}$/,
            message: '请输入字母与数字'
        }
    ];
    return (
        <div className={styles.jobRankEditWrapper}>
            <Card
                bordered={false}
                className={styles.card}
                bodyStyle={{ padding: '0 16px 16px' }}
                extra={
                    <BottomAction>
                        <Button onClick={handleCancel} style={{ marginRight: 8 }}>
                            取消
                        </Button>
                        <Button
                            type="primary"
                            loading={category === 'postRankType' ? flowRankTypeLoading : flowRankLoading}
                            disabled={category === 'postRankType' ? flowRankTypeLoading : flowRankLoading}
                            onClick={handleSubmit}
                        >
                            下一步
                        </Button>
                    </BottomAction>
                }
            >
                {pageTitle && (
                    <header className={styles.pageTitle}>
                        <p>{pageTitle}</p>
                    </header>
                )}
                <Card bodyStyle={{ padding: '0 16px 16px' }} style={{ margin: 24 }} bordered={false}>
                    <Row className={styles.mainContent}>
                        <Col xl={20}>
                            <div className={styles.formLayout}>
                                <div className={styles.title}>基础信息</div>
                                <Form {...formLayout} style={{ display: 'flex', flexDirection: 'column' }}>
                                    <div style={{ width: '80%' }}>
                                        {!isPostRankType && (
                                            <Form.Item label="职级序列">
                                                {getFieldDecorator('rankTypeName', {
                                                    // rules: requiredRules('职级序列'),
                                                    initialValue: rankTypeNameState
                                                })(<div>{rankTypeNameState}</div>)}
                                            </Form.Item>
                                        )}

                                        <Form.Item label="申请日期">
                                            {getFieldDecorator('applyDate', {
                                                // rules: requiredRules('申请日期'),
                                                initialValue: moment().format('YYYY-MM-DD')
                                            })(<div>{moment().format('YYYY-MM-DD')}</div>)}
                                        </Form.Item>

                                        <Form.Item label="制度名称">
                                            {getFieldDecorator('institutionName', {
                                                // rules: requiredRules('制度名称'),
                                                initialValue: '职级管理制度'
                                            })(<div>职级管理制度</div>)}
                                        </Form.Item>

                                        <Form.Item label="制度类型">
                                            {getFieldDecorator('institutionType', {
                                                // rules: requiredRules('制度类型'),
                                                initialValue: 'personnel'
                                            })(
                                                <Select disabled>
                                                    <Select.Option value="personnel">人事制度</Select.Option>
                                                </Select>
                                            )}
                                        </Form.Item>

                                        <Form.Item label="制度编号" help="2-40个字符">
                                            {getFieldDecorator('institutionNo', {
                                                rules: [...requiredRules('制度编号'), rangeRules(2, 40)]
                                            })(<Input placeholder="请输入制度编号" maxLength={40} />)}
                                        </Form.Item>

                                        <Form.Item label="制度简介" help="2-200个字符">
                                            {getFieldDecorator('institutionIntroduce', {
                                                rules: [...requiredRules('制度简介'), rangeRules(2, 200)]
                                            })(
                                                <Input.TextArea rows={5} maxLength={200} placeholder="请输入制度简介" />
                                            )}
                                        </Form.Item>

                                        <Form.Item label="生效日期" style={{ marginBottom: 0 }}>
                                            {getFieldDecorator('auditEffectFlag', {
                                                rules: requiredRules('生效日期'),
                                                initialValue: auditEffectFlagEnum.immediateEffect
                                            })(
                                                <Radio.Group>
                                                    <Radio value={auditEffectFlagEnum.immediateEffect}>
                                                        审核通过即可生效
                                                    </Radio>
                                                    <Radio value={auditEffectFlagEnum.effectiveOnTime}>
                                                        指定日期生效
                                                    </Radio>
                                                </Radio.Group>
                                            )}
                                            {form.getFieldValue('auditEffectFlag') ===
                                                auditEffectFlagEnum.effectiveOnTime &&
                                                getFieldDecorator('startTime', {
                                                    rules: requiredRules('指定日期生效'),
                                                    initialValue: startTimeValue || moment().add(1, 'days')
                                                })(<DatePicker format="YYYY-MM-DD" disabledDate={disabledDate} />)}
                                        </Form.Item>
                                    </div>
                                </Form>
                                <Divider />

                                <div className={styles.title}>制度内容</div>
                                <Form {...formLayout}>
                                    <div style={{ width: '80%' }}>
                                        {isPostRankType && (
                                            <>
                                                <Form.Item label="职级序列" help="2-50个字符">
                                                    {getFieldDecorator('rankTypeName', {
                                                        rules:
                                                            type === 'delete'
                                                                ? []
                                                                : [...requiredRules('职级序列'), rangeRules(2, 50)]
                                                    })(
                                                        <Input
                                                            disabled={type === 'delete'}
                                                            placeholder="请输入职级序列，不超过 50 个字"
                                                            maxLength={50}
                                                        />
                                                    )}
                                                </Form.Item>
                                                <Form.Item label="描述" help="2-1000个字符">
                                                    {getFieldDecorator('rankTypeDesc', {
                                                        rules:
                                                            type === 'delete'
                                                                ? []
                                                                : [...requiredRules('描述'), rangeRules(2, 1000)]
                                                    })(
                                                        <Input.TextArea
                                                            disabled={type === 'delete'}
                                                            rows={5}
                                                            maxLength={1000}
                                                            placeholder="请输入职级序列描述，不超过 1000 字"
                                                        />
                                                    )}
                                                </Form.Item>
                                            </>
                                        )}

                                        {!isPostRankType && (
                                            <>
                                                <Form.Item label="职级名称" help="2-50个字符">
                                                    {getFieldDecorator('rankName', {
                                                        rules:
                                                            type === 'delete'
                                                                ? []
                                                                : [...requiredRules('职级名称'), rangeRules(2, 50)]
                                                    })(
                                                        <Input
                                                            placeholder="请输入职级名称"
                                                            disabled={type === 'delete'}
                                                            maxLength={50}
                                                        />
                                                    )}
                                                </Form.Item>
                                                <Form.Item label="职级">
                                                    {getFieldDecorator('rankValue', {
                                                        rules: type === 'delete' ? [] : rankValueRule(requiredRules)
                                                    })(
                                                        <Input
                                                            placeholder="请输入字母与数字"
                                                            maxLength={10}
                                                            disabled={type === 'delete'}
                                                        />
                                                    )}
                                                </Form.Item>
                                                <Form.Item label="描述" help="2-1000个字符">
                                                    {getFieldDecorator('rankDesc', {
                                                        rules: type === 'delete' ? [] : [rangeRules(2, 1000)]
                                                    })(
                                                        <Input.TextArea
                                                            rows={5}
                                                            disabled={type === 'delete'}
                                                            maxLength={1000}
                                                            placeholder="请输入职级描述，不超过 1000 字"
                                                        />
                                                    )}
                                                </Form.Item>
                                                {/* <Form.Item label="评定维度" required={type !== 'delete'}>
                                                    {getFieldDecorator('rankDimensions', {
                                                        rules: type === 'delete' ? [] : rankDimensionsRules()
                                                    })(<Dimension readOnly={type === 'delete'} />)}
                                                </Form.Item> */}
                                            </>
                                        )}

                                        <Form.Item label="原因" help="2-200个字符">
                                            {getFieldDecorator('modifyRemark', {
                                                rules: [...requiredRules('原因'), rangeRules(2, 200)]
                                            })(
                                                <Input.TextArea
                                                    rows={5}
                                                    maxLength={200}
                                                    placeholder="请输入原因，不超过 200 字"
                                                />
                                            )}
                                        </Form.Item>
                                    </div>
                                </Form>
                            </div>
                        </Col>
                    </Row>
                </Card>
            </Card>
        </div>
    );
};

export default Form.create({ name: 'JobRankEdit' })(JobRankEdit);
